<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\BaseController;
use app\middleware\admin\Auth;
use app\model\Admins;
use app\model\Classroom as ClassroomMdoel;
use app\model\ClassStudent;
use app\model\ClassTime;
use app\model\School;
use app\model\Ticketuse;
use app\model\TimeLog;
use think\Exception;
use think\facade\Db;
use think\facade\Request;

class Classroom extends BaseController
{

    protected $middleware=[Auth::class];

    public function index($limit = 10)
    {
        $name = request()->param('name');
        $status = request()->param('status');
        $time = request()->param('time');
        $school_id=request()->param('school_id');
        $data = ClassroomMdoel::with(['school'=>function($query){
            $query->field('id,name');
        }])->where('school_id',$school_id)->when($name, function ($query) use ($name) {
            $query->where('name', 'like', "%$name%");
        })->when($status, function ($query) use ($status) {
            $query->where('status', $status);
        })->when($time, function ($query) use ($time) {
            $query->whereBetween('create_time',$time);
        })->order('sort', 'desc')->paginate($limit);
        return $this->success($data);
    }

    /** 時間表
     * @param
     * @return \think\response\Json
     */
    public function classTime()
    {

        $data = Array();
        $timeData = null;
        $name = null;
        $teacherName = null;
        $date = [];
        $state = request()->param('state','課室') ;
        $time = request()->get('timestamp');
        $dateTab = request()->get('isShowTabel');
        $schoolId = request()->get('schoolId');
        $id = request()->get('id');
        if (request()->get('name') != '') $name = request()->get('name');
        if (request()->get('teacherName') != '') $teacherName =request()->get('teacherName');
        if ($time == '') $time = date('Y-m-d', time()) . " 00:00:00";

        if ($dateTab == 2) {
            $timestamp = strtotime($time);
            $mdays = date('t', $timestamp);
            //生成当月开始时间和结束时间
            $startTime = date('Y-m-01', $timestamp);
            $endTime = date('Y-m-' . $mdays, $timestamp);
            $sunday = date('Y-m-d', (strtotime($startTime) - (date('w', strtotime($startTime)) == 0 ? 7 : date('w', strtotime($startTime))) * 24 * 3600)); //获取当月1号的星期一时间
            $days = round((strtotime($startTime) - strtotime($sunday)) / 3600 / 24); //获取星期天到1号的天数
            $monthDay = round((strtotime($endTime) - strtotime($startTime)) / 3600 / 24) + 1; //获取当月的天数
            $number = (int)substr($sunday, 8, 2);
            $timeDate['start_time'] = $startTime . ' 00:00:00';
            $timeDate['end_time'] = $endTime . ' 23:59:59';
            $timeTableData = [];
            $data = [];
            $tab = 0;
            if ($days != 0) {
                for ($i = 0; $i < $days; $i++) {
                    $arr = [];
                    $arr['number'] = $number;
                    $arr['classhourData'] = [];
                    $timeTableData[$tab] = $arr;
                    $number++;
                    $tab++;
                }
            }
//            $model = new ClassTime();
//            $classhourData = $model->getList($schoolId, $timeDate, $name, $teacherName);

//            $classhourData=ClassTime::with(['classStudent'=>function($q) use($name,$teacherName){
//                   $a= $q->with(['student'=>function($q) use($name){
//
//                    }]);
//            },'room','teacher','course'])
//                ->select()->toArray();

            $classhourData=$this->getStudentInfo($teacherName,$name,$timeDate,$schoolId,$id);

            $time = date('Y-m-d', strtotime($timeDate['start_time']));
            for ($k = 0; $k < $monthDay; $k++) {
                $arr = [];
                $arr['number'] = $k + 1;
                $arr['classhourData'] = [];
                if (!empty($classhourData[0])) {
                    foreach ($classhourData as $key=>$v) {

                        if (date('Y-m-d', strtotime($v['start_time'])) == $time) {

                            $v['time'] = substr($v['start_time'], 11, 5) . '-' . substr($v['end_time'], 11, 5);
                            $v['startTime'] = $v['start_time'];
//                            $NumberPeople = explode('/', $v['NumberPeople']);
                            $room=\app\model\Course::where('id',$v['course_id'])->value('num');

                            $person=count($v['classStudent']);
                            $NumberPeople = [$person,$room];  //模拟

                            if ($NumberPeople[0] == $NumberPeople[1]) {
                                $v['class_student_info_count'] = $NumberPeople[0] .'/'. $NumberPeople[1];
                            } else {
                                $v['class_student_info_count'] = $NumberPeople[0].'/' . $NumberPeople[1];
                            }
                            $arr['classhourData'][] = $v;
                        }
                    }
                }
                $timeTableData[$tab] = $arr;
                $tab++;
                if ($tab == 7) {
                    $data[] = $timeTableData;
                    $timeTableData = [];
                    $tab = 0;
                }
                $time = date('Y-m-d', strtotime("$time+1day"));
            }
            if ($tab != 0) {
                $data[] = $timeTableData;
            }
            return $this->success($data);
        } else {

            $weekArray = array("日", "一", "二", "三", "四", "五", "六");
            if ($dateTab == 0) {
                //按天获取数据
                $classroomData = [];
                $timeDate['start_time'] = date('Y-m-d', strtotime($time)) . " 00:00:00";
                $timeDate['end_time'] = date('Y-m-d', strtotime("$time+1day")) . " 00:00:00";
                $date[0]['time'] = substr($timeDate['start_time'], 0, 4) . '年' . substr($timeDate['start_time'], 5, 2) . "月" . substr($timeDate['start_time'], 8, 2) . "日 星期" . $weekArray[date('w', strtotime($timeDate['start_time']))];

                if ($state == '課室') {
                    $sort = 'sort';
                    $classroom = new \app\model\Classroom();
                    $classroomData = $classroom->getList1($timeDate, $schoolId, $name, $teacherName,$id);

                } else if ($state == '教師') {
                    $sort = 'id';
                    $admin = new Admins();
                    $classroomData = $admin->getData1($timeDate, $schoolId, $name, $teacherName,$id);

                }
                $ticket = new Ticketuse();
                $ticketClassroomData = $ticket->getTicketClassroom($timeDate, $schoolId, $name,$id);
//                dd($ticketClassroomData);
                if (!empty($ticketClassroomData[0])) {
                    foreach ($ticketClassroomData as $q) {
                        $tab = true;
                        foreach ($classroomData as $p) {
                            if ($p['id'] == $q['id']) {
                                $tab = false;
                            }
                        }
                        if ($tab) {
                            $classroomData[] = $q;
                        }
                    }
                }

                if (!empty($classroomData[0])) {
                    $last_names = array_column($classroomData, $sort);
                    array_multisort($last_names, SORT_ASC, $classroomData);
                    $date[0]['classroomData'] = $classroomData;
                } else {
                    $date[0]['classroomData'][] = ['name' => '教室', 'id' => 1, 'color' => '#000'];
                }
            } else if ($dateTab == 1) {
                //按星期获取数据
                $w = date('w', strtotime($time));
                $week_start = date('Y-m-d', strtotime("$time -" . ($w ? $w - 0 : 6) . ' days'));
                $timeDate['start_time'] = $week_start . " 00:00:00";
                $timeDate['end_time'] = date('Y-m-d', strtotime("$week_start +7 days")) . " 00:00:00";
                $startTime = $timeDate['start_time'];
                $timeSlot = ['start_time' => $timeDate['start_time'], 'end_time' => date('Y-m-d', strtotime("$startTime + 1day")) . " 00:00:00"];
                for ($i = 0; $i < 7; $i++) {
                    $headerData = [];
                    $date[$i]['time'] = substr($startTime, 0, 4) . '年' . substr($startTime, 5, 2) . "月" . substr($startTime, 8, 2) . "日 星期" . $weekArray[date('w', strtotime($startTime))];
                    $startTime = date('Y-m-d', strtotime("$startTime + 1day"));
                    if ($state == '課室') {
                        $sort = 'sort';

//                        $classroom = new Classroom();
//                        $headerData = $classroom->getData($timeSlot, $schoolId, $name, $teacherName);
                        $classroom = new \app\model\Classroom();
                        $headerData = $classroom->getList1($timeSlot, $schoolId, $name, $teacherName,$id);

                    } else if ($state == '教師') {
                        $sort = 'id';
                        $admin = new Admins();
                        $headerData = $admin->getData1($timeSlot, $schoolId, $name, $teacherName,$id);

                    }
                    $ticket = new Ticketuse();
                    $ticketClassroomData = $ticket->getTicketClassroom($timeSlot, $schoolId, $name);

                    if (!empty($ticketClassroomData[0])) {
                        foreach ($ticketClassroomData as $q) {
                            $tab = true;
                            foreach ($headerData as $p) {
                                if ($p['id'] == $q['id']) {
                                    $tab = false;
                                }
                            }
                            if ($tab) {
                                $headerData[] = $q;
                            }
                        }
                    }

                    if (!empty($headerData[0])) {
                        $last_names = array_column($headerData, $sort);
                        array_multisort($last_names, SORT_ASC, $headerData);
                        $date[$i]['classroomData'] = $headerData;
                    } else {
                        $date[$i]['classroomData'][] = ['name' => '教室', 'id' => 1, 'color' => ''];
                    }
                    $timeSlot['start_time'] = date('Y-m-d', strtotime("$startTime")) . " 00:00:00";
                    $timeSlot['end_time'] = date('Y-m-d', strtotime("$startTime + 1day")) . " 00:00:00";
                }
            }

            if ($state == '課室') {
                $stateKey = 'classroom_id';
                $fieldName = 'classroomName';
            } else if ($state == '教師') {
                $stateKey = 'admin_id';
                $fieldName = 'teacher_name';
            }
//            $model = new Classhour();
//            $classhourData = $model->getList($schoolId, $timeDate, $name, $teacherName);
//            $classhourData=ClassTime::with(['classStudent'=>function($q){
//                $q->with('student');
//            },'room','teacher','course'])->select()->toArray();
            $classhourData=$this->getStudentInfo($teacherName,$name,$timeDate,$schoolId,$id);

            $ticket = new Ticketuse();
            $ticketData = $ticket->getUsedTicket($timeDate, ['t.school_id' => $schoolId], $name);

            $timeTableData = [
                ['height' => 60, 0 => '07:00'],
                ['height' => 60, 0 => '08:00'],
                ['height' => 60, 0 => '09:00'],
                ['height' => 60, 0 => '10:00'],
                ['height' => 60, 0 => '11:00'],
                ['height' => 60, 0 => '12:00'],
                ['height' => 60, 0 => '13:00'],
                ['height' => 60, 0 => '14:00'],
                ['height' => 60, 0 => '15:00'],
                ['height' => 60, 0 => '16:00'],
                ['height' => 60, 0 => '17:00'],
                ['height' => 60, 0 => '18:00'],
                ['height' => 60, 0 => '19:00'],
                ['height' => 60, 0 => '20:00'],
                ['height' => 60, 0 => '21:00'],
                ['height' => 60, 0 => '22:00'],
                ['height' => 60, 0 => '23:00'],
                ['height' => 60, 0 => '24:00'],
                []
            ];

            foreach ($date as $value) {
                foreach ($value['classroomData'] as $val) {
                    $tab = mb_substr($value['time'], 8, 2);
                    foreach ($timeTableData as &$v) {
                        $name=empty($val['ename']) ? '導師':$val['ename'];
                        $arr = ['tab' => $tab, $stateKey => $val['id'], $fieldName => $name, 'color' => $val['color']];
                        $v[][0] = $arr;
                    }
                }
            }
            if (!empty($classhourData[0]) || !empty($ticketData[0])) {
                foreach ($timeTableData as $k => $val) {
                    foreach ($val as $key => $value) {
                        if ($key === 0 && $k != 18) {
                            foreach ($classhourData as $v) {

                                $start_time = substr($v['start_time'], 11, 2) . ':00';
                                if ($start_time == $value) {
                                    $totalHeight = 60 + count($v['classStudent']) * 25;

                                    $hour = ((int)substr($v['start_time'], 14, 2) + $v['duration']) / 60;
                                    for ($i = 0; $i <= $hour; $i++) {
                                        $h = 0;
                                        if ((int)substr($v['end_time'], 11, 2) > ((int)substr($value, 0, 2) + $i)) {
                                            if ((int)substr($v['start_time'], 11, 2) == $value) {
//                                                $h = (60 - (int)substr($v['start_time'], 14, 2)) * $totalHeight / $v['duration'] + (int)substr($v['start_time'], 14, 2);
//                                                $h=60;
                                            } else {
                                                $h = $totalHeight / $v['duration'] * 60;
                                            }
                                        } else {
                                            $h = (int)substr($v['end_time'], 14, 2) * $totalHeight / $v['duration'] + (60 - (int)substr($v['end_time'], 14, 2));
                                        }
                                        if ($v['duration'] < 60) {
//                                            $h = $h * 60 / $v['duration'];
                                            $h=60;
                                        }
                                        if (!empty($timeTableData[($k + $i)]['height'])) {
                                            if ($h > $timeTableData[($k + $i)]['height']) {
                                                $timeTableData[($k + $i)]['height'] = $h;
                                            }
                                        } else {
                                            $timeTableData[($k + $i)]['height'] = $h;
                                        }
                                    }
                                }
                            }
                            foreach ($ticketData as $y) {
                                $start_time = substr($y['start_time'], 11, 2) . ':00';

                                $minute = floor((strtotime($y['end_time']) - strtotime($y['start_time'])) % 86400 / 60);

                                $height = 240 - $minute * 4;

                                if ($start_time == $value && $minute <= 60 && $timeTableData[$k]['height'] < $height) {

                                    $timeTableData[$k]['height'] = $height;
                                }
                            }
                        }
                    }
                }
                unset($timeTableData[18]);
                unset($timeTableData[19]);
                // return $classhourData;
                foreach ($timeTableData as $k => &$val) {
                    // return $val;

                    foreach ($val as $key => &$value) {

                        if ($key != 'height') {
                            foreach ($classhourData as &$v) {

                                $tab = substr($v['start_time'], 8, 2);
                                if (isset($value[0]['tab']) && isset($value[0][$stateKey])) {
                                    if ($value[0]['tab'] == $tab && $value[0][$stateKey] == $v[$stateKey] && $key != 0) {
                                        $keyTab = !empty($value[0]['id']) ? count($value) : 0;
                                        $start_time = substr($v['start_time'], 11, 2) . ':00';
                                        if ($start_time == $val[0]) {

                                            $v['courses_name'] = $v['course_name'];
                                            $hour = ((int)substr($v['start_time'], 14, 2) + $v['duration']) / 60;
                                            $height = 0;
                                            if ($hour <= 1) {
                                                $height += $v['duration'] * $timeTableData[$k]['height'] / 60;
                                            } else {
                                                for ($i = 0; $i <= $hour; $i++) {
                                                    if ($i == 0) {
                                                        $height += (60 - (int)substr($v['start_time'], 14, 2)) * $timeTableData[($k + $i)]['height'] / 60;
                                                    } else if (($hour - $i) >= 1) {
                                                        $height += $timeTableData[($k + $i)]['height'];
                                                    } else {
                                                        $height += (int)substr($v['end_time'], 14, 2) * $timeTableData[($k + $i)]['height'] / 60;
                                                    }
                                                }
                                            }
                                            $v['date'] = substr($v['start_time'], 0, 10);
                                            $time = strtotime($v['start_time']) - strtotime(substr($v['start_time'], 0, 10) . ' ' . $val[0] . ':00');
                                            $startMin = $time / 60;
                                            $time = strtotime($v['end_time']) - strtotime(substr($v['start_time'], 0, 10) . ' ' . $val[0] . ':00');
                                            $endMin = $time / 60;
                                            $min = $endMin - $startMin;
//                                            $style = 'height: ' . 200 . 'px;color: rgb(255, 255, 255);outline:white solid 1px;font-size: 10pt;background-color: ' . $value[0]['color'] . ';width:100%;position:absolute;top:0;left:0;z-index:99;';
//                                              $style=  'background-color: ' . $value[0]['color'].';height: ' . 200 . 'px';
                                            $style=  'background-color: ' . $value[0]['color'];

                                            $v['startTime'] = $v['start_time'];
                                            $v['start_time'] = substr($v['start_time'], 11, 5);
                                            $v['end_time'] = substr($v['end_time'], 11, 5);
                                            $v['style'] = $style;
                                            $v['tab'] = $value[0]['tab'];

                                            $room=\app\model\Course::where('id',$v['course_id'])->value('num');
                                            $person=count($v['classStudent']);


                                            $NumberPeople = [$person,$room];  //模拟

                                            if ($NumberPeople[0] == $NumberPeople[1]) {
                                                $v['class_student_info_count'] = $NumberPeople[0] .'/' . $NumberPeople[1];
                                            } else {
                                                $v['class_student_info_count'] = $NumberPeople[0] .'/'. $NumberPeople[1];
                                            }
//                                            $NumberPeople = explode('/', $v['NumberPeople']);
//                                            if ($NumberPeople[0] == $NumberPeople[1]) {
//                                                $v['class_student_info_count'] = '滿/' . $NumberPeople[1];
//                                            } else {
//                                                $v['class_student_info_count'] = '未滿/' . $NumberPeople[1];
//                                            }

                                            if (!empty($value[0]['color'])) {
                                                $v['color'] = $value[0]['color'];
                                            }
                                            $v['type'] = 'course';
                                            $value[$keyTab] = $v;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if (!empty($ticketData[0]) && $stateKey == 'classroom_id') {
                foreach ($timeTableData as $k => &$val) {
                    foreach ($val as $key => &$value) {
                        if ($key != 'height') {
                            foreach ($ticketData as &$j) {
                                $tab = substr($j['start_time'], 8, 2);
                                if (isset($value[0]['tab']) && isset($value[0]['classroom_id'])) {

                                    if ($value[0]['tab'] == $tab && $value[0]['classroom_id'] == $j['cId'] && $key != 0) {
                                        $start_time = substr($j['start_time'], 11, 2) . ':00';
                                        if ($start_time == $val[0]) {
                                            $keyTab = !empty($value[0]['id']) ? count($value) : 0;
                                            $hour = ((int)substr($j['start_time'], 14, 2) + ($j['number'] * 30)) / 60;
                                            $height = 0;
                                            if ($hour < 1) {
                                                $height = $hour * $timeTableData[$k]['height'];
                                            } else {
                                                for ($i = 0; $i <= $hour; $i++) {
                                                    if ($i == 0) {
                                                        $height += (60 - (int)substr($j['start_time'], 14, 2)) * $timeTableData[($k + $i)]['height'] / 60;
                                                    } else if (($hour - $i) >= 1) {
                                                        if (!empty($timeTableData[($k + $i)]['height'])) {
                                                            $height += $timeTableData[($k + $i)]['height'];
                                                        } else {
                                                            $height += 60;
                                                        }
                                                    } else {
                                                        if (!empty($timeTableData[($k + $i)]['height'])) {
                                                            $height += (int)substr($j['end_time'], 14, 2) * $timeTableData[($k + $i)]['height'] / 60;
                                                        } else {
                                                            $height += (int)substr($j['end_time'], 14, 2);
                                                        }

                                                    }
                                                }
                                            }
                                            $time = strtotime($j['start_time']) - strtotime(substr($j['start_time'], 0, 10) . ' ' . $val[0] . ':00');
                                            $startMin = $time / 60;
                                            $style = 'margin-top:' . (int)($startMin / 60 * $val['height']) . 'px;height: ' . $height . 'px;color: rgb(255, 255, 255);outline:white solid 1px;font-size: 10pt;background-color: orange;width:100%;position:absolute;top:0;left:0;z-index:99;';
                                            $j['startTime'] = $j['start_time'];
                                            $j['start_time'] = substr($j['start_time'], 11, 5);
                                            $j['end_time'] = substr($j['end_time'], 11, 5);
                                            $j['style'] = $style;
                                            $j['type'] = 'ticket';
                                            $j['classroomName'] = $j['name'];
                                            $j['color'] = $value[0]['color'];
                                            $j['classroom_id'] = $value[0]['classroom_id'];
                                            $j['tab'] = $value[0]['tab'];
                                            $value[$keyTab] = $j;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            $data['timeData'] = $date;
            $data['timeTableData'] = $timeTableData;
            $width = (count($timeTableData[0]) - 1) * 220 + 50;
            $data['tableStyle'] = 'width:' . $width . 'px;margin-top: 20px;font-size: 10pt;border:1px solid rgb(179, 179, 179);font-family: "微軟正黑體"';
            return $this->success($data);
        }
    }

    protected function getStudentInfo($teacherName='',$name='',$timeDate,$schoolId,$id)
    {
        $data = Classtime::alias('ct')
            ->leftJoin('course s', 'ct.course_id = s.id')
            ->leftJoin('admins a', 'a.id = ct.admin_id')
            ->leftJoin('class_student ', 'class_student.classtime_id = ct.id')
            ->leftJoin('student sd','sd.id=class_student.student_id')
            ->leftJoin('classroom cr','cr.id=ct.classroom_id')
            ->where('a.name','like',"%$teacherName%")
            ->where('sd.name','like',"%$name%")
            ->whereBetween('ct.start_time',[$timeDate['start_time'], $timeDate['end_time']])
            ->where('cr.school_id',$schoolId)
            ->where('class_student.state','<>','取消')
            ->when($id, function ($query) use ($id) {
                $query->where('class_student.student_id', $id);
            })
//                ->field('st.*, s.name as course_name, a.name as teacher_name')
            ->field('DISTINCT ct.*, s.name as course_name, a.ename as teacher_name,cr.name as roomname')
            ->order('start_time')
            ->select()
            ->toArray();

        $classStudent = ClassStudent::where('type', 1)
            ->alias('cs')
            ->leftJoin('student sd','sd.id=cs.student_id')
            ->field('cs.*,sd.name,sd.sex,sd.birthday,sd.mobile,sd.education')
            ->select()->toArray();

        $classtimeIds = array_column($data, 'id');
        $classStudentGrouped = [];
        foreach ($classStudent as $cs) {
            $classtimeId = $cs['classtime_id'];
            if (in_array($classtimeId, $classtimeIds)) {
                $classStudentGrouped[$classtimeId][] = $cs;
            }
        }

        foreach ($data as &$item) {
            $classtimeId = $item['id'];
            $item['classStudent'] = isset($classStudentGrouped[$classtimeId]) ? $classStudentGrouped[$classtimeId] : [];
        }

        return $data;
    }

    /**
     * 修改时间表状态
     * @param $id
     * @return \think\response\Json
     */
    public function edit()
    {
        $params = request()->param();
        $AdminName=Admins::where('id',\request()->userid)->value('ename');
//        Db::startTrans();
        if(!empty($params['admin_id'])){

            ClassTime::where('id',$params['id'])->update(['admin_id'=>$params['admin_id']]);
//            return $this->success();
        }
        foreach ($params['student'] as $item) {

            $name=\app\model\Student::where('id',$item['student_id'])->value('name');
            if ($item['state'] == '調堂') {

                $class = ClassTime::alias('ct')
                    ->join('class_student cs', 'cs.classtime_id=ct.id')
                    ->join('classroom cr', 'cr.id=ct.classroom_id', 'left')
                    ->join('invoice_details ind', 'ind.id=cs.invoice_details_id', 'left')
                    ->join('invoice i', 'i.id=ind.invoice_id', 'left')
                    ->where('i.status', 1)
                    ->where('ind.status', 1)
                    ->where('ct.admin_id', $item['admin_id'])
                    ->where('ct.classroom_id', $item['classroom_id'])
                    ->where('ct.course_id', $item['course_id'])
                    ->where('ct.start_time', $item['start_time'])
                    ->where('ct.end_time', $item['end_time'])
                    ->where('cs.type', 1)
                    ->where('cs.state', '<>', '取消')
                    ->field('ct.*')
                    ->find();

                if ($class) {
                    $tab = ClassStudent::where('classtime_id', $class['id'])->where('student_id', $item['student_id'])->where('type', 1)->find();
                    if ($tab) { //需要判断是否已加入
                        Db::rollback();
                        throw new Exception("該學生已經加入該時間段的課程，請勿重複操作");
                    }
                    ClassStudent::where('id', $item['classStudentid'])->update(['classtime_id' => $class['id']]);
                    $teacher=Admins::where('id',$item['admin_id'])->value('ename');
                    $room=\app\model\Classroom::where('id',$item['classroom_id'])->value('name');
                    TimeLog::create([
                        'school_id'=>$params['school_id'],
                        'classtime_id'=>$class['id'],
                        'content'=>'在' . date('Y-m-d h:i:s', time()) . '時，' . $AdminName . '管理員修改了學生:' . $name . '的課時狀態為調堂，並修改課時時間為：' . $item['start_time'] . '-' . $item['end_time'] . '課時的教師為：' . $teacher . ',教室为：' . $room
                    ]);
                } else {

                    $tab = $this->repeatedVerification($item['admin_id'], $item['classroom_id'], $item['start_time'], $item['end_time'], null, $params['school_id']);
                    if ($tab) {
                        $name = School::where('id', $params['school_id'])->value('name');
                        throw new Exception('在' . $name . '分校内的' . $item['start_time'] . '到' . $item['end_time'] . '時間段內選擇的老師或教室已被佔用，請重新規劃時間');
                    }
                    $classtime = ClassTime::create([
                        'admin_id' => $item['admin_id'],
                        'classroom_id' => $item['classroom_id'],
                        'course_id' => $item['course_id'],
                        'time1' => '',
                        'date' => "",
                        'start_time' => $item['start_time'],
                        'end_time' => $item['end_time'],
                        'state' => '調堂'
                    ]);
                    ClassStudent::where('id', $item['classStudentid'])->update(['classtime_id' => $classtime->id]);
                    $teacher=Admins::where('id',$item['admin_id'])->value('ename');
                    $room=\app\model\Classroom::where('id',$item['classroom_id'])->value('name');
                    TimeLog::create([
                        'school_id'=>$params['school_id'],
                        'classtime_id'=>$classtime->id,
                        'content'=>'在' . date('Y-m-d h:i:s', time()) . '時，' . $AdminName . '管理員修改了學生:' . $name . '的課時狀態為調堂，並修改課時時間為：' . $item['start_time'] . '-' . $item['end_time'] . '課時的教師為：' . $teacher . ',教室为：' . $room
                    ]);
                }

            }else{

                foreach($params['student'] as $v){
                    ClassStudent::where('classtime_id',$v['classStudentid'])->where('student_id',$v['student_id'])->update([
                        'status'=>$v['status'] ?? 1,
                        'state'=>$v['state'],
                        'lastmin'=>$v['lastMin'] ??''
                    ]);
                }
            }

//        }
            return $this->success();
//        try {
//            ClassTime::where('id',$id)->update(['remark'=>$params['remark'] ?? '']);
//
//
//            Db::commit();
//            return $this->success();
//        }catch (\Exception $e){
//            Db::rollback();
//        }

        }
    }

    /**
     * 操作记录
     * @param $limit
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function timeLog($limit=15)
    {
        $school_id=\request()->param('school_id');
        $name=\request()->param('name');
        $data=TimeLog::where('school_id',$school_id)->when($name,function ($q)use($name){
            $q->where('content','like',"%$name%");
        })->paginate($limit);

        return $this->success($data);
    }

    public function timeLogDel($id)
    {
        TimeLog::where('id',$id)->delete();
        return $this->success();
    }

    protected function repeatedVerification($admin_id, $classroom_id, $startTime, $endTime, $id = null, $school_id = null)
    {


        $start = ClassTime::alias('ct')
            ->join('class_student cs', 'cs.classtime_id = ct.id')
            ->join('invoice_details ind', 'ind.id = cs.invoice_details_id', 'left')
            ->join('invoice i', 'i.id = ind.invoice_id', 'left')
            ->join('student s', 'i.student_id = s.id', 'left')
            ->where('i.status', 1)
            ->where('ind.status', 1)
            ->where(function ($q) use ($school_id) {
                if ($school_id != null) {
                    $q->where('i.school_id', $school_id);
                }
            })
            ->where('ct.admin_id',$admin_id)
            ->where('ct.classroom_id',$classroom_id)
            ->where('ct.start_time',$startTime)
            ->where('ct.end_time',$endTime)
            ->where('ct.course_id','<>',$id)
            ->count();

        if($start){
            return true;
        }
            return false;

    }

    /**
     * 获取未点名名单
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function getAppeared($limit=15)
    {
        $name = request()->param('name');
        $time = request()->param('time');
        $school_id=\request()->param('school_id');
      $data=  Db::name('class_student')->alias('cs')
            ->leftJoin('classtime ct','ct.id=cs.classtime_id')
            ->leftJoin('student s','s.id=cs.student_id')
            ->leftJoin('classroom cr','cr.id=ct.classroom_id')
            ->leftJoin('admins a','a.id=ct.admin_id')
            ->leftJoin('course c','ct.course_id=c.id')
            ->when($name,function($q) use($name){
                $q->whereRaw("(concat(IFNULL(s.name,''),IFNULL(a.name,''),IFNULL(cr.name,'')) like '%" . $name . "%')");
            })
            ->when($time,function ($q)use($time){
                $q->whereBetween('cs.create_time',$time);
            })

            ->where('cs.state','未點名')
            ->where('cr.school_id',$school_id)
            ->field('cs.*,a.name as teacher_name,cr.name room_name,s.name student_name,c.name,c.hour,c.num,c.id as course_id')
            ->order('cs.create_time')
            ->paginate($limit);
      return $this->success($data);
    }

    public function create()
    {
        ClassroomMdoel::create(request()->param());
        return $this->success();
    }


    public function update($id)
    {
        ClassroomMdoel::where('id',$id)->update(request()->param());
        return $this->success();
    }


    public function delete($id)
    {
        ClassroomMdoel::where('id','in',$id)->delete();
        return $this->success();
    }


}
